<template>
  <el-dialog :title="titleText" :visible="showDialog" @close="cancel">
    <el-form ref="roleFormRef" :model="formData" :rules="roleRules">
      <el-form-item label="角色名称" prop="name" label-width="120px">
        <el-input
          v-model="formData.name"
          style="width: 80%"
          placeholder="请输入角色名称"
        />
      </el-form-item>
      <el-form-item label="角色描述" prop="description" label-width="120px">
        <el-input
          v-model="formData.description"
          style="width: 80%"
          placeholder="请输入角色描述"
        />
      </el-form-item>
      <el-form-item style="text-align: center; margin-top: 30px;">
        <el-button type="info" @click="cancel">取消</el-button>
        <el-button type="primary" @click="confirm">确定</el-button>
      </el-form-item>
    </el-form>
  </el-dialog>
</template>

<script>
import { updateRoleById, getRoleDetail, addRole } from '@/api/setting'

export default {
  name: 'RoleDialog',
  props: {
    showDialog: {
      type: Boolean,
      default: false
    },
    roleId: {
      type: String,
      default: ''
    }
  },
  data() {
    return {
      formData: {
        name: '', // 角色名称
        description: '' // 角色描述
      },
      roleRules: {
        name: [{ required: true, message: '请输入角色名称', trigger: 'blur' }],
        description: [
          { required: true, message: '请输入角色描述', trigger: 'blur' }
        ]
      }
    }
  },
  computed: {
    titleText() {
      return this.roleId ? '编辑角色' : '添加角色'
    }
  },
  watch: {
    async roleId(value) {
      if (value) {
        const result = await getRoleDetail(this.roleId)
        this.formData = result
        this.formData.id = this.roleId
      }
    }
  },
  methods: {
    confirm() {
      this.$refs.roleFormRef.validate(async isOK => {
        if (isOK) {
          try {
            if (this.roleId) {
              await updateRoleById(this.formData)
              this.$message.success('更新角色成功')
            } else {
              await addRole(this.formData)
              this.$message.success('添加角色成功')
            }
            // 通知主页面刷新当前角色列表
            this.$emit('updateRoles')
            this.cancel()
          } catch (err) {
            this.$message.warning(err.message)
          }
        }
      })
    },
    cancel() {
      this.$refs.roleFormRef.resetFields()
      // 清空 roleId
      this.$emit('clearRoleId', '')
      // 关闭弹框
      this.$emit('update:showDialog', false)
    }
  }
}
</script>
